package top.zy.moredatabase.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;

import javax.sql.DataSource;

/**
 * @author ZackYoung
 * @version 1.0
 * @date 2022/1/6
 */
@Order(-1)
@Aspect
@Component
public class ChooseD {
    @Pointcut("@annotation(top.zy.moredatabase.aop.ChooseDataSource)")
    public void ds() {
    }

    @Before("ds()")
    public void switchDataSource(JoinPoint joinPoint) throws Throwable {
        DynamicDataSourceContextHolder.push("mysql84");
    }

    @After("ds()")
    public void restoreDataSource(JoinPoint point) {
        // 将数据源置为默认数据源
        DynamicDataSourceContextHolder.poll();
        System.out.println("Restore DataSource to [" + DynamicDataSourceContextHolder.peek()
                + "] in Method [" + point.getSignature() + "]");
    }

}
